import Vue from "vue";
import axios from "axios";
import router from "../router";



// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  timeout: 60 * 1000, // Timeout
  withCredentials: true // Check cross-site Access-Control
};


const _$http = axios.create(config); // no auto 500 error UI

Plugin.install = function(Vue) {
  Vue.$http = _$http; // no auto 500 error UI
  Object.defineProperties(Vue.prototype, {
    $http: {
      get() {
        return _$http; // no auto 500 error UI
      }
    }
  });
};

let user_name,user_token;
_$http.interceptors.request.use(
  // no auto 500 error UI
  function(config) {
    // Do something before request is sent
    if (config.url.includes("/login") === false) {
      if (!user_token) {
        const user = JSON.parse(window.sessionStorage.getItem("user"));
        if (!user) {
          Vue.prototype.$alert("登录失效,请重新登录！", "提示", {
            confirmButtonText: "确定",
            callback: () => {
              router.push("/login");
            }
          });
          return;
        }
        user_name = user.userName;
        user_token = user.userToken;
      }
      if (user_token && config.headers.common["user_token"] == null) {
        config.headers.common["user_token"] = user_token;
        config.headers.common["user_name"] = user_name;
      }
    } else {
      user_token = null;
      user_name = null;
    }
    return config;
  },
  function(error) {
    // Do something with request error
    Vue.prototype.$notify({
      showClose: true,
      message: error,
      type: "error"
    });
    return Promise.reject(error);
  }
);

Vue.use(Plugin);

export default Plugin;
